import React, { useState, useEffect, useRef } from 'react';
import type { Product } from '../../types/product';
import { uploadFile, createProduct, updateProduct } from '../../Api/product';
import './ProductForm.css';

interface ProductFormProps {
  visible: boolean;
  onClose: () => void;
  product: Partial<Product> | null;
  onSuccess: () => void;
}

// 定义一个更具体的类型来代替 "any"，以解决 linter 错误
/*
type ProductPayload = Partial<Omit<Product, 'name' | 'declaredName' | 'declaredValue'>> & {
  productName?: string;
  englishName?: string;
  declaredPrice?: number;
};
*/

// 定义API荷载的精确类型
interface ApiPayload {
  id?: number;
  teamId?: number;
  categoryId?: number;
  productTypeId?: number;
  productName?: string;
  sku?: string;
  specification?: string;
  purchasePrice?: number;
  sellingPrice?: number;
  stockAlert?: number;
  weight?: number;
  brand?: string;
  model?: string;
  englishName?: string;
  customsCode?: string;
  declaredPrice?: number;
  length?: number;
  width?: number;
  height?: number;
  status?: number;
  notes?: string;
  photo?: string;
}

const ProductForm: React.FC<ProductFormProps> = ({ visible, onClose, product, onSuccess }) => {
  const [formData, setFormData] = useState<Partial<Product>>({});
  const [loading, setLoading] = useState(false);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [validated, setValidated] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    // 当弹窗变为可见时，根据是否有product来初始化或重置表单
    if (visible) {
      setValidated(false); // 重置验证状态
      if (product) {
        // 编辑模式：加载产品数据
        setFormData(product);
        setPreviewImage(product.photo || null);
      } else {
        // 新增模式：重置为空表单，并设置默认状态
        setFormData({ status: '1' });
        setPreviewImage(null);
      }
    }
  }, [product, visible]);

  if (!visible) {
    return null;
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    // 对于数字输入框，即使为空也尝试转换为数字或保持为空字符串
    const isNumberInput = (e.target as HTMLInputElement).type === 'number';
    const finalValue = isNumberInput ? (value === '' ? '' : Number(value)) : value;

    setFormData(prev => ({ ...prev, [name]: finalValue }));
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setLoading(true);
      try {
        const imageUrl = await uploadFile(file);
        if (typeof imageUrl === 'string' && imageUrl.startsWith('http')) {
          setFormData(prev => ({ ...prev, photo: imageUrl }));
          setPreviewImage(imageUrl);
          alert('图片上传成功');
        } else {
          alert(`图片上传失败: 无效的返回格式. ${imageUrl}`);
        }
      } catch (error) {
        console.error("图片上传失败:", error);
        alert(`图片上传失败: ${(error as Error).message}`);
      } finally {
        setLoading(false);
      }
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = e.currentTarget;

    setValidated(true); // 激活验证样式

    if (form.checkValidity() === false) {
      e.stopPropagation();
      alert('请填写所有必填项。');
      return;
    }

    setLoading(true);

    // 直接、显式地构建最终的 API 荷载
    const payload: ApiPayload = {};

    // 字段映射和类型转换
    if (product?.id) payload.id = product.id;
    if (formData.name) payload.productName = formData.name;
    if (formData.englishName) payload.englishName = formData.englishName;
    if (formData.sku) payload.sku = formData.sku;
    if (formData.specification) payload.specification = formData.specification;
    if (formData.brand) payload.brand = formData.brand;
    if (formData.model) payload.model = formData.model;
    if (formData.customsCode) payload.customsCode = formData.customsCode;
    if (formData.notes) payload.notes = formData.notes;
    if (formData.photo) payload.photo = formData.photo;

    // --- 数字和长整型 ---
    // parseInt 用于整型和长整型字段
    if (formData.teamId) payload.teamId = parseInt(String(formData.teamId), 10);
    if (formData.categoryId) payload.categoryId = parseInt(String(formData.categoryId), 10);
    if (formData.productTypeId) payload.productTypeId = parseInt(String(formData.productTypeId), 10);
    if (formData.stockAlert) payload.stockAlert = parseInt(String(formData.stockAlert), 10);
    
    // 价格字段，确保为整数 (分)
    payload.purchasePrice = formData.purchasePrice ? parseInt(String(formData.purchasePrice), 10) : 0;
    payload.sellingPrice = formData.sellingPrice ? parseInt(String(formData.sellingPrice), 10) : 0;
    payload.declaredPrice = formData.declaredPrice ? parseInt(String(formData.declaredPrice), 10) : 0;

    // 尺寸和重量字段，确保为整数
    if (formData.weight) payload.weight = parseInt(String(formData.weight), 10);
    if (formData.length) payload.length = parseInt(String(formData.length), 10);
    if (formData.width) payload.width = parseInt(String(formData.width), 10);
    if (formData.height) payload.height = parseInt(String(formData.height), 10);
    
    // 如果是新增模式，设置默认状态并移除id
    if (!product) {
      delete payload.id;
      payload.status = formData.status ? parseInt(String(formData.status)) : 1; // 默认为启用
    } else {
       if (formData.status) payload.status = parseInt(String(formData.status));
    }

    try {
      console.log('发送到API的数据:', payload);
      const apiCall = product ? updateProduct : createProduct;
      const response = await apiCall(payload);
      if (response.code === 200) {
        alert(product ? '修改成功' : '新增成功');
        onSuccess();
        onClose();
      } else {
        alert(response.message || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      alert(`操作失败: ${(error as Error).message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-overlay">
      <div className="modal-container">
        <div className="modal-header">
          <h2>{product ? '修改产品' : '新增产品'}</h2>
          <button onClick={onClose} className="close-button">&times;</button>
        </div>
        <form onSubmit={handleSubmit} className={`product-form ${validated ? 'was-validated' : ''}`} noValidate>
          <div className="form-grid">
            <div className="form-group">
              <label>产品名称*</label>
              <input name="name" value={formData.name || ''} onChange={handleChange} required />
            </div>
            <div className="form-group">
              <label>SKU*</label>
              <input name="sku" value={formData.sku || ''} onChange={handleChange} required />
            </div>
            <div className="form-group">
              <label>英文名称</label>
              <input name="englishName" value={formData.englishName || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>团队</label>
              <select name="teamId" value={formData.teamId || ''} onChange={handleChange} required={!product}>
                <option value="">请选择</option>
                <option value="1">运营一部</option>
                <option value="2">运营二部</option>
                <option value="3">市场部</option>
              </select>
            </div>
            <div className="form-group">
              <label>类别</label>
              <select name="categoryId" value={formData.categoryId || ''} onChange={handleChange} required={!product}>
                <option value="">请选择</option>
                <option value="1">电子产品</option>
                <option value="2">家居用品</option>
                <option value="3">户外运动</option>
                <option value="4">美妆个护</option>
              </select>
            </div>
            <div className="form-group">
              <label>产品类型</label>
              <select name="productTypeId" value={formData.productTypeId || ''} onChange={handleChange} required={!product}>
                  <option value="">请选择</option>
                  <option value="1">手机</option>
                  <option value="2">笔记本电脑</option>
                  <option value="3">智能手表</option>
                  <option value="4">蓝牙耳机</option>
              </select>
            </div>
            <div className="form-group">
              <label>规格</label>
              <input name="specification" value={formData.specification || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>品牌</label>
              <input name="brand" value={formData.brand || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>型号</label>
              <input name="model" value={formData.model || ''} onChange={handleChange} required={!product} />
            </div>
             <div className="form-group">
              <label>入库价(分)</label>
              <input name="purchasePrice" type="number" value={formData.purchasePrice || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>出库价(分)</label>
              <input name="sellingPrice" type="number" value={formData.sellingPrice || ''} onChange={handleChange} required={!product} />
            </div>
             <div className="form-group">
              <label>申报价值(分)</label>
              <input name="declaredPrice" type="number" value={formData.declaredPrice || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>库存预警</label>
              <input name="stockAlert" type="number" value={formData.stockAlert || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>重量(克)</label>
              <input name="weight" type="number" value={formData.weight || ''} onChange={handleChange} required={!product} />
            </div>
             <div className="form-group">
              <label>长度(毫米)</label>
              <input name="length" type="number" value={formData.length || ''} onChange={handleChange} required={!product} />
            </div>
             <div className="form-group">
              <label>宽度(毫米)</label>
              <input name="width" type="number" value={formData.width || ''} onChange={handleChange} required={!product} />
            </div>
             <div className="form-group">
              <label>高度(毫米)</label>
              <input name="height" type="number" value={formData.height || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
              <label>海关编码</label>
              <input name="customsCode" value={formData.customsCode || ''} onChange={handleChange} required={!product} />
            </div>
            <div className="form-group">
               <label>状态</label>
               <div className="radio-group">
                <label>
                  <input
                    type="radio"
                    name="status"
                    value="1"
                    checked={String(formData.status) === '1'}
                    onChange={handleChange}
                  />
                  启用
                </label>
                <label>
                  <input
                    type="radio"
                    name="status"
                    value="0"
                    checked={String(formData.status) === '0'}
                    onChange={handleChange}
                  />
                  禁用
                </label>
              </div>
            </div>
            <div className="form-group form-group-full">
              <label>图片上传</label>
              <div className="image-upload-container">
                <button type="button" className="btn btn-default" onClick={() => fileInputRef.current?.click()}>
                  选择文件
                </button>
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleFileChange}
                  style={{ display: 'none' }}
                  accept="image/*"
                />
                {previewImage && <img src={previewImage} alt="预览" className="image-preview" />}
                 {/* 隐藏的输入框，用于表单验证 */}
                <input type="text" value={formData.photo || ''} required={!product} style={{width: 0, height: 0, border: 'none', padding: 0}} readOnly/>
              </div>
            </div>
            <div className="form-group form-group-full">
              <label>备注</label>
              <textarea name="notes" value={formData.notes || ''} onChange={handleChange} />
            </div>
          </div>
          <div className="modal-footer">
            <button type="button" onClick={onClose} className="btn btn-default">取消</button>
            <button type="submit" className="btn btn-primary" disabled={loading}>
              {loading ? '保存中...' : '确认'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ProductForm; 